<template>
    <div class="chart-container">
        <div v-for="i in 3" :key="i" class="chart-box">
            <div ref="chartRefs" class="chart" />
        </div>
    </div>
</template>
<script setup>
import { onMounted, onUnmounted, ref, nextTick } from 'vue';
import * as echarts from 'echarts';

// 创建多个图表容器引用
const chartRefs = ref([]);
let chartInstances = [];

// 图表配置选项 - 垂直柱形图
const getChartOption = (title, data) => ({
    title: { text: title },
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', data: ['A', 'B', 'C', 'D', 'E'] },
    yAxis: { type: 'value' },
    series: [{
        type: 'bar',
        data: data,
        label: { show: true, position: 'top' },
        itemStyle: { color: () => `hsl(${Math.random() * 360}, 70%, 60%)` }
    }]
});

// 初始化图表
const initCharts = () => {
    // 确保DOM已更新且容器有尺寸
    const checkAndInit = () => {
        const hasValidDimensions = chartRefs.value.every(el => {
            return el && el.clientWidth > 0 && el.clientHeight > 0;
        });

        if (hasValidDimensions) {
            // 清除现有实例
            chartInstances.forEach(chart => chart.dispose());
            chartInstances = [];

            // 初始化新图表
            chartRefs.value.forEach((el, index) => {
                if (el) {
                    const chart = echarts.init(el);
                    const data = [30, 40, 35, 50, 49].map(v => v + Math.floor(Math.random() * 20));
                    chart.setOption(getChartOption(`图表 ${index + 1}`, data));
                    chartInstances.push(chart);
                }
            });
        } else {
            // 重试直到获取有效尺寸
            requestAnimationFrame(checkAndInit);
        }
    };

    nextTick(checkAndInit);
};

// 初始化图表
onMounted(initCharts);

// 响应窗口大小变化
window.addEventListener('resize', () => {
    chartInstances.forEach(chart => chart.resize());
});

// 清理图表实例
onUnmounted(() => {
    chartInstances.forEach(chart => chart.dispose());
    window.removeEventListener('resize', () => {});
});
</script>

<style scoped>

</style>
